package com.fruit.auth.web.action;


import static com.fruit.util.ValidateUtil.isValidate;
import static com.fruit.util.ValidateUtil.validateLength;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.fruit.auth.model.User;
import com.fruit.auth.service.PrivilegeService;
import com.fruit.auth.service.UserService;
import com.fruit.util.Constants;
import com.fruit.web.action.util.BaseAction;
@Controller
@Scope("prototype")
public class LoginAction extends BaseAction<User>
{
	
	private static final long serialVersionUID = -3608575305255335096L; 
	
	private User user;
	
	@Resource(name="userService")
	private UserService userService;
	
	@Resource(name="privilegeService")
	private PrivilegeService privilegeService;
	
	public void setUser(User user)
	{
		this.user = user;
	}
	
	public String login()
	{
		HttpServletRequest request=getRequest();
		String accessMethod=request.getMethod();
		if(accessMethod.equals("GET"))
		{
			return "login";
		}
		else if(accessMethod.equals("POST"))
			return doLogin(request);
		return ERROR;
	}
	
	private String doLogin(HttpServletRequest req)
	{
		
		String username=user.getUsername();
		String password=user.getPassword();
		if(!isValidate(username)||!isValidate(password))
		{
			ajaxMsg.setStatus(Constants.INPUT_INVALID);
			ajaxMsg.setMsg("用户名或密码不能为空");
		}
		else if(!validateLength(username, 4, 32)||!validateLength(password, 6, 32))
		{
			ajaxMsg.setStatus(Constants.LOGIN_FAILED);
			ajaxMsg.setMsg("用户名或密码错误");
		}
		else
		{
			User u=userService.login(username,password);
			if(u==null)
			{
				ajaxMsg.setStatus(Constants.LOGIN_FAILED);
				ajaxMsg.setMsg("用户名或密码错误");
			}
			else
			{
				//认证通过，加载权限
				u.setPrivilegeSum(new long[privilegeService.getMaxPrivilegePos()+1]);
				userService.authUserPrivileges(u);
				ajaxMsg.setStatus(Constants.LOGIN_SUCCESS);
				getSession().setAttribute("user", u);
				
			}
		}
		renderJson(ajaxMsg);
		return NONE;
	}

	@Override
	public void prepare() throws Exception
	{
		user=new User();
	}
	
	@Override
	public User getModel()
	{
		return user;
	}
}
